<template>
  <div class="statistics-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="overview-card">
          <template #header>
            <div class="card-header">
              <h3>高速公路管理系统 - 统计分析</h3>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8" v-for="(item, index) in statisticsData" :key="index">
              <div class="data-item" :style="{ borderColor: item.color }">
                <el-icon :size="40" :color="item.color">
                  <component :is="item.icon"></component>
                </el-icon>
                <div class="data-info">
                  <div class="data-title">{{ item.title }}</div>
                  <div class="data-value">{{ item.value }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>路段状态分布</h3>
            </div>
          </template>
          <div class="chart-container" ref="statusChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>事故类型统计</h3>
            </div>
          </template>
          <div class="chart-container" ref="accidentTypeChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>事故严重程度分析</h3>
            </div>
          </template>
          <div class="chart-container" ref="severityChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>高速公路限速分布</h3>
            </div>
          </template>
          <div class="chart-container" ref="speedLimitChartRef"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { Position, Warning, Tools } from '@element-plus/icons-vue'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Query from '@arcgis/core/rest/support/Query.js'

// 图表实例
let statusChart: echarts.ECharts | null = null
let accidentTypeChart: echarts.ECharts | null = null
let severityChart: echarts.ECharts | null = null
let speedLimitChart: echarts.ECharts | null = null

// 图表容器引用
const statusChartRef = ref<HTMLElement | null>(null)
const accidentTypeChartRef = ref<HTMLElement | null>(null)
const severityChartRef = ref<HTMLElement | null>(null)
const speedLimitChartRef = ref<HTMLElement | null>(null)

// 统计数据
const statisticsData = ref([
  { title: '路段总数', value: '0', icon: 'Position', color: '#67C23A' },
  { title: '事故警报', value: '0', icon: 'Warning', color: '#E6A23C' },
  { title: '维修路段', value: '0', icon: 'Tools', color: '#F56C6C' },
])

// 图层相关变量
let highwayLayer: FeatureLayer | null = null
let accidentLayer: FeatureLayer | null = null

// 初始化图层
const initLayers = () => {
  // 创建高速公路图层
  highwayLayer = new FeatureLayer({
    url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/0',
    outFields: ['*'],
  })

  // 创建事故点图层
  accidentLayer = new FeatureLayer({
    url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/1',
    outFields: ['*'],
  })
}

// 更新统计数据
const updateStatistics = async () => {
  if (!highwayLayer || !accidentLayer) return

  try {
    // 获取路段总数
    const totalQuery = new Query()
    totalQuery.where = '1=1'
    totalQuery.outFields = ['*']
    totalQuery.returnGeometry = false
    const totalResult = await highwayLayer.queryFeatures(totalQuery)
    statisticsData.value[0].value = totalResult.features.length.toString()

    // 获取事故警报数量
    const accidentQuery = new Query()
    accidentQuery.where = '1=1'
    accidentQuery.outFields = ['*']
    accidentQuery.returnGeometry = false
    const accidentResult = await accidentLayer.queryFeatures(accidentQuery)
    statisticsData.value[1].value = accidentResult.features.length.toString()

    // 获取维修中的路段数量
    const maintenanceQuery = new Query()
    maintenanceQuery.where = "status = '维修中'"
    maintenanceQuery.outFields = ['*']
    maintenanceQuery.returnGeometry = false
    const maintenanceResult = await highwayLayer.queryFeatures(maintenanceQuery)
    statisticsData.value[2].value = maintenanceResult.features.length.toString()
  } catch (error) {
    console.error('更新统计数据失败:', error)
    ElMessage.error('更新统计数据失败')
  }
}

// 初始化路段状态分布图表
const initStatusChart = async () => {
  if (!highwayLayer || !statusChartRef.value) return

  try {
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['status']
    query.returnGeometry = false
    const result = await highwayLayer.queryFeatures(query)

    // 统计各状态数量
    const statusMap = new Map<string, number>()
    result.features.forEach((feature) => {
      const status = feature.attributes.status || '未知'
      statusMap.set(status, (statusMap.get(status) || 0) + 1)
    })

    // 准备图表数据
    const chartData = Array.from(statusMap).map(([name, value]) => ({ name, value }))

    // 初始化图表
    statusChart = echarts.init(statusChartRef.value)
    statusChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: Array.from(statusMap.keys()),
      },
      series: [
        {
          name: '路段状态',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: chartData,
        },
      ],
    })
  } catch (error) {
    console.error('初始化路段状态分布图表失败:', error)
    ElMessage.error('初始化路段状态分布图表失败')
  }
}

// 初始化事故类型统计图表
const initAccidentTypeChart = async () => {
  if (!accidentLayer || !accidentTypeChartRef.value) return

  try {
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['accident_type']
    query.returnGeometry = false
    const result = await accidentLayer.queryFeatures(query)

    // 统计各类型数量
    const typeMap = new Map<string, number>()
    result.features.forEach((feature) => {
      const type = feature.attributes.accident_type || '未知'
      typeMap.set(type, (typeMap.get(type) || 0) + 1)
    })

    // 准备图表数据
    const types = Array.from(typeMap.keys())
    const values = Array.from(typeMap.values())

    // 初始化图表
    accidentTypeChart = echarts.init(accidentTypeChartRef.value)
    accidentTypeChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          data: types,
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series: [
        {
          name: '事故数量',
          type: 'bar',
          barWidth: '60%',
          data: values,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' },
            ]),
          },
        },
      ],
    })
  } catch (error) {
    console.error('初始化事故类型统计图表失败:', error)
    ElMessage.error('初始化事故类型统计图表失败')
  }
}

// 初始化事故严重程度分析图表
const initSeverityChart = async () => {
  if (!accidentLayer || !severityChartRef.value) return

  try {
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['severity', 'accident_type']
    query.returnGeometry = false
    const result = await accidentLayer.queryFeatures(query)

    // 统计各严重程度和类型的关系
    const severityTypes = ['轻微', '一般', '严重', '特别严重']
    const accidentTypes = new Set<string>()
    const dataMap = new Map<string, Map<string, number>>()

    // 初始化数据结构
    severityTypes.forEach((severity) => {
      dataMap.set(severity, new Map<string, number>())
    })

    // 统计数据
    result.features.forEach((feature) => {
      const severity = feature.attributes.severity || '未知'
      const type = feature.attributes.accident_type || '未知'
      accidentTypes.add(type)

      if (dataMap.has(severity)) {
        const typeMap = dataMap.get(severity)!
        typeMap.set(type, (typeMap.get(type) || 0) + 1)
      }
    })

    // 准备图表数据
    const types = Array.from(accidentTypes)
    const series = severityTypes.map((severity) => {
      const typeMap = dataMap.get(severity) || new Map()
      return {
        name: severity,
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          position: 'inside',
        },
        emphasis: {
          focus: 'series',
        },
        data: types.map((type) => typeMap.get(type) || 0),
      }
    })

    // 初始化图表
    severityChart = echarts.init(severityChartRef.value)
    severityChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: {
        data: severityTypes,
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: types,
      },
      yAxis: {
        type: 'value',
      },
      series: series,
    })
  } catch (error) {
    console.error('初始化事故严重程度分析图表失败:', error)
    ElMessage.error('初始化事故严重程度分析图表失败')
  }
}

// 初始化高速公路限速分布图表
const initSpeedLimitChart = async () => {
  if (!highwayLayer || !speedLimitChartRef.value) return

  try {
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['speed_limit', 'highway_name']
    query.returnGeometry = false
    const result = await highwayLayer.queryFeatures(query)

    // 准备图表数据
    const data = result.features.map((feature) => ({
      name: feature.attributes.highway_name,
      value: parseInt(feature.attributes.speed_limit) || 0,
    }))

    // 初始化图表
    speedLimitChart = echarts.init(speedLimitChartRef.value)
    speedLimitChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'value',
        name: '限速(km/h)',
        nameLocation: 'middle',
        nameGap: 30,
      },
      yAxis: {
        type: 'category',
        data: data.map((item) => item.name),
        axisLabel: {
          interval: 0,
          rotate: 30,
        },
      },
      series: [
        {
          name: '限速值',
          type: 'bar',
          data: data.map((item) => item.value),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              { offset: 0, color: '#ffde33' },
              { offset: 0.5, color: '#ff9933' },
              { offset: 1, color: '#cc0033' },
            ]),
          },
        },
      ],
    })
  } catch (error) {
    console.error('初始化高速公路限速分布图表失败:', error)
    ElMessage.error('初始化高速公路限速分布图表失败')
  }
}

// 初始化所有图表
const initAllCharts = async () => {
  await updateStatistics()
  await initStatusChart()
  await initAccidentTypeChart()
  await initSeverityChart()
  await initSpeedLimitChart()
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  statusChart?.resize()
  accidentTypeChart?.resize()
  severityChart?.resize()
  speedLimitChart?.resize()
}

onMounted(() => {
  initLayers()
  initAllCharts()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  statusChart?.dispose()
  accidentTypeChart?.dispose()
  severityChart?.dispose()
  speedLimitChart?.dispose()
})
</script>

<style scoped>
.statistics-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.overview-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-top: 4px solid #409eff;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-top: 4px solid #67c23a;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.chart-container {
  height: 320px;
  width: 100%;
}

.data-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-left: 4px solid;
  transition: transform 0.3s;
}

.data-item:hover {
  transform: translateY(-5px);
}

.data-info {
  margin-left: 15px;
}

.data-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 5px;
}

.data-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}
</style>